package com.company.ThreadPoolDemo;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 作者  Administrator
 * 时间  2017/6/2 11:13
 * 文件  ThreadPoolsDemo
 * 描述  创建一个定时的线程池
 */
public class ScheduThreadPool {

	public static void main(String[] args) {
//		scheduTest();
		sigleSchedu();
	}

	/**
	 * 这里创建了两个线程
	 */
	public static void scheduTest(){
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
		//延迟2秒后执行该任务
		scheduledThreadPool.schedule(new Runnable() {
			@Override
			public void run() {
				String threadName = Thread.currentThread().getName();
				System.out.println("线程："+threadName+",正在执行任务");
			}
		}, 2, TimeUnit.SECONDS);
		//延迟1秒后，每隔2秒执行一次该任务
		scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				String threadName = Thread.currentThread().getName();
				System.out.println("线程："+threadName+",正在执行重复任务");
			}
		}, 1, 2, TimeUnit.SECONDS);
	}

	/**
	 * 一个延时任务
	 * 一个重复任务
	 * 共用一个线程
	 */
	public static void sigleSchedu(){
		ScheduledExecutorService singleThreadScheduledPool = Executors.newSingleThreadScheduledExecutor();
		singleThreadScheduledPool.schedule(new Runnable() {
			@Override
			public void run() {
				String threadName = Thread.currentThread().getName();
				System.out.println("线程："+threadName+",正在执行定时任务");
			}
		}, 2, TimeUnit.SECONDS);
		//延迟1秒后，每隔2秒执行一次该任务
		singleThreadScheduledPool.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				String threadName = Thread.currentThread().getName();
				System.out.println("线程：" + threadName + ",正在执行重复");
			}
		},1,2,TimeUnit.SECONDS);
	}
}


